package edu.iyte.ceng431.hw2.pos.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import edu.iyte.ceng431.hw2.pos.db.Search;
import edu.iyte.ceng431.hw2.pos.model.Product;
import edu.iyte.ceng431.hw2.pos.model.Register;
import edu.iyte.ceng431.hw2.pos.view.MainFrame;
import edu.iyte.ceng431.hw2.pos.view.PaymentDialog;

public class RegisterController {

	private PaymentDialog paymentDialog;
	private MainFrame mainView;
	private Register register;
	private PaymentController paymentController;

	public RegisterController(MainFrame mainView, Register register) {
		super();

		this.mainView = mainView;
		this.register = register;
		this.mainView.addLineItemListener(new LineItemListener());
		this.mainView.addEndSaleListener(new EndSaleListener());
		this.mainView.setVisible(true);
		new ReturnController(mainView);
		paymentDialog = new PaymentDialog(this.mainView, true, Double
				.parseDouble(this.mainView.getTotalTextField().getText()));
		paymentController = new PaymentController(paymentDialog, this.register);
		new ReportController(mainView);
	}

	class LineItemListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			try {
				int productId = Integer.parseInt(mainView
						.getProductIdTextField().getText());
				int quantity = Integer.parseInt(mainView.getQuantityTextField()
						.getText());
				Product product = Search.getProduct(productId);
				if (product == null || quantity < 1) {
					throw new NumberFormatException();
				}
				register.notifyNewSaleLineItem(product, quantity);

			} catch (NumberFormatException nfex) {
				JOptionPane.showMessageDialog(mainView,
						"Invalid Product ID or Quantity.", "Error",
						JOptionPane.ERROR_MESSAGE);
			}
		}
	}

	class EndSaleListener implements ActionListener {

		public void actionPerformed(ActionEvent e) {
			paymentDialog.getCashTextField().setText(
					mainView.getTotalTextField().getText());
			paymentController.setTotal(Double.parseDouble(mainView
					.getTotalTextField().getText()));
			paymentDialog.setVisible(true);
		}
	}
}